# write point pattern into one file with specific formate accepted by
# pattern reconstruction software writen by Prof. Thorsten Wiegand
# 
# data.ppp: a ppp class point data pattern
# covr    : (optional) a intensity map, e.g. intensity of all points or effect map of 
# 			covraiates
# filename: the name of the point coordination file. it should be a "*.dat" file.
# 			if covr is provided, the file of covr will be "cov_*.dat".
#           path of the intensity file will be as same as the give dat file.
#
# Author: Guochun Shen
# Data:   2011-12-20
# Project:spatial statistic
# Email:  shenguochun@gmail.com
###############################################################################

write_prerec_file=function(data.ppp,covr=NULL,filename,...){
	#setup the line break for windows user
	if(LINUX)
		eol="\r\n"
	else
		eol="\n"
	plotinf=matrix(c(0,data.ppp$win$xrange[2],0,
					data.ppp$win$yrange[2],data.ppp$n),nrow=1,ncol=5)
	write.table(plotinf,filename,row.names=FALSE,col.names=FALSE,eol=eol,...)
	points=cbind(data.ppp$x,data.ppp$y)
	write.table(points,filename,row.names=FALSE,col.names=FALSE,eol=eol,
			append=TRUE,quote=FALSE,...)
	if(!is.null(covr)){
		temp=strsplit(filename,split="/")[[1]]
		temp=temp[length(temp)]
		pre=strsplit(filename,split=temp)[[1]]
		temp=strsplit(temp,split=".dat")
		filename.covr=paste(pre,"cov_",temp,".int",sep="")
		ngrid=covr$dim
		grid_size=covr$xstep
		plotinf2=c(1,ngrid[2],1,ngrid[1],prod(ngrid),grid_size)
		plotinf2=matrix(plotinf2,nrow=1)
		xy=expand.grid(y=1:ngrid[1],x=1:ngrid[2])
		xy=xy[,c(2,1)]
		#normalize the covraite map
		covr$v=covr$v/max(covr$v,na.rm=T)
		density=cbind(xy,rep(1,dim(xy)[1]),round(as.numeric(covr$v),6))
		write.table(plotinf2,filename.covr,row.names=FALSE,col.names=FALSE,eol=eol,...)
		write.table(density,filename.covr,row.names=FALSE,col.names=FALSE,eol=eol,
				append=TRUE,quote=FALSE,...)
	}
}

